<template>
  <div class="characters">
    <div class="characters-list">
      <el-scrollbar view-class="el-scrollbar-view" max-height="100vh">
        <div v-for="(item, index) in characters" :key="index" class="characters-item" @click="clickCharacter(item, index)">
          <el-icon v-if="editIndex < 0" @click.stop="deleteCharactersItem(index)"><i-ep-Delete /></el-icon>
          <div class="characters-item-info">
            <strong class="characters-item-name">{{ item.name }}</strong>
            <span class="characters-item-gender">{{ item.gender }}</span>
            <span class="characters-item-age">{{ item.age }}</span>
          </div>
          <p class="characters-item-des">{{ item.profile }}</p>
        </div>
        <span v-if="!characters.length" class="no-data">无数据</span>
      </el-scrollbar>
    </div>
    <div class="characters-edit">
      <el-scrollbar height="calc(100vh - 77px)">
        <el-form ref="ruleFormRef" :model="characterForm" label-position="top">
          <el-form-item label="姓名">
            <el-input v-model="characterForm.name" placeholder="请输入人物姓名" maxlength="15" :show-word-limit="true" />
          </el-form-item>
          <el-form-item label="性别">
            <el-radio-group v-model="characterForm.gender">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="characterForm.age" type="number" :max="999999999999" placeholder="请输入人物年龄" />
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="characterForm.profile" type="textarea" placeholder="请输入人物简介" maxlength="1000" resize="none" :show-word-limit="true" :rows="10" />
          </el-form-item>
          <el-form-item label="关系">
            <el-table :data="characterForm.relationship" empty-text="无数据" border size="small">
              <el-table-column prop="name" label="人物" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.name" no-data-text="无数据" placeholder="请选择人物">
                    <template v-for="(item, index) in characters" :key="index">
                      <el-option v-if="item.name !== characterForm.name" :label="item.name" :value="item.name" />
                    </template>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="relationship" label="关系" align="center" width="110">
                <template #default="scope">
                  <el-input v-model="scope.row.relationship" placeholder="请输入关系" maxlength="10" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="60">
                <template #default="scope">
                  <el-button link type="primary" size="small" @click.prevent="deleteRelationshipRow(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button class="relationship-add-btn" @click="clickAddRelationship">新增</el-button>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <div v-if="editIndex >= 0" class="characters-btns">
        <el-button @click="clickCancel">取消</el-button>
        <el-button type="primary" @click="clickAddOrEdit">确认</el-button>
      </div>
      <div v-else class="characters-btns">
        <el-button :disabled="disabled" type="primary" @click="clickAddOrEdit">新增</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 人物谱管理页面
 */
import { ref, reactive, watch, onMounted, toRaw } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css";
import "element-plus/es/components/message-box/style/css";
import { useBookStore } from "@/store/modules/bookStore";
const bookStore = useBookStore();

interface Relationship {
  name: string;
  relationship: string;
}
interface Characters {
  id?: number;
  name: string;
  gender: string;
  age: number;
  profile: string;
  relationship: Relationship[];
}
const defaultCharacterForm = () => {
  return {
    name: "",
    gender: "男",
    age: 20,
    profile: "",
    relationship: []
  };
};
const characterForm = reactive<Characters>(defaultCharacterForm());
// 所有人物
const characters = ref<Characters[]>([]);
// 当前编辑人物索引
const editIndex = ref(-1);
// 按钮是否禁用状态
const disabled = ref(true);
watch(
  () => characterForm.name,
  (e: string) => {
    disabled.value = !e;
  }
);

let bookInfo: any = {};
onMounted(() => {
  // 读取配置文件中的大纲相关数据
  if (bookStore.bookPath) {
    window.electronAPI.readFile(bookStore.bookPath + "/mzBook.json").then((res) => {
      if (res) {
        bookInfo = JSON.parse(res);
        if (bookInfo.characters) {
          bookInfo.characters.forEach((ele: Characters, index: number) => {
            characters.value.push({
              id: index + 1,
              ...ele
            });
          });
        } else {
          characters.value = [];
        }
        console.log(characters.value);
      }
    });
  }
});

// 点击新增或编辑确认
const clickAddOrEdit = () => {
  if (editIndex.value >= 0) {
    // 编辑更新
    characters.value[editIndex.value] = {
      ...toRaw(characterForm)
    };
  } else {
    // 新增
    characters.value.push({
      ...toRaw(characterForm)
    });
  }
  bookInfo = {
    ...bookInfo,
    characters: toRaw(characters.value)
  };
  window.electronAPI.writeFile(bookStore.bookPath + "/mzBook.json", JSON.stringify(bookInfo)).then((res) => {
    if (res) {
      Object.assign(characterForm, defaultCharacterForm());
    }
  });
};
// 删除人物
const deleteCharactersItem = (i: number) => {
  ElMessageBox.confirm(`确认要删除“${characters.value[i].name}”吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      characters.value.splice(i, 1);
      bookInfo = {
        ...bookInfo,
        characters: toRaw(characters.value)
      };
      window.electronAPI.writeFile(bookStore.bookPath + "/mzBook.json", JSON.stringify(bookInfo)).then((res) => {
        if (res) {
          ElMessage({
            type: "success",
            message: "已删除"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
// 点击人物，查看人物详情
const clickCharacter = (e: Characters, i: number) => {
  Object.assign(characterForm, e);
  editIndex.value = i;
};
// 取消编辑
const clickCancel = () => {
  Object.assign(characterForm, defaultCharacterForm());
  editIndex.value = -1;
};
// 添加关系
const clickAddRelationship = () => {
  characterForm.relationship.push({
    name: "",
    relationship: ""
  });
};
// 删除关系
const deleteRelationshipRow = (i: number) => {
  characterForm.relationship.splice(i, 1);
};
</script>

<style lang="scss" scoped>
.characters {
  display: flex;
  justify-content: space-between;
  &-list {
    flex: 1;
    height: 100vh;
    padding: 0px 0px 0px 15px;
    box-sizing: border-box;
    position: relative;
    .el-scrollbar {
      width: 100%;
    }
    :deep(.el-scrollbar-view) {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      align-content: flex-start;
      padding: 15px 0px 0px;
    }
    .no-data {
      position: absolute;
      left: 50%;
      top: 45%;
      transform: translate(-50%, -50%);
      font-size: 80px;
    }
  }
  &-item {
    width: 300px;
    height: 178px;
    border: 1px solid var(--el-border-color);
    border-radius: 10px;
    margin-right: 15px;
    margin-bottom: 15px;
    cursor: pointer;
    padding: 15px;
    box-sizing: border-box;
    font-size: 16px;
    box-shadow: var(--el-box-shadow-light);
    position: relative;
    &:hover,
    &.active {
      border-color: var(--el-color-primary);
    }
    &-name {
      font-size: 20px;
      margin-right: 15px;
    }
    &-gender {
      margin-right: 15px;
    }
    &-des {
      margin-top: 5px;
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 5;
      -webkit-box-orient: vertical;
    }
    &:hover {
      .el-icon {
        display: block;
      }
    }
    .el-icon {
      display: none;
      position: absolute;
      right: 15px;
      top: 15px;
      font-size: 18px;
    }
  }
  &-edit {
    width: 340px;
    height: 100vh;
    border-left: 1px solid var(--el-border-color);
    box-sizing: border-box;
    padding: 15px 15px 62px;
    overflow: auto;
    position: relative;
    .el-button {
      width: 100%;
    }
    .relationship-add-btn {
      margin-top: 5px;
    }
  }
  &-btns {
    width: 100%;
    display: flex;
    position: absolute;
    bottom: 0px;
    left: 0px;
    padding: 15px;
    box-sizing: border-box;
    background-color: var(--el-bg-color);
    .el-button {
      flex: 1;
    }
  }
}
</style>
